<template>
	<div class="login">
	  <Header title="注册" />
	  <div class="img">买团</div>
	  <van-form @submit="onSubmit">
		<van-field
			v-model="data.username"
			name="user"
			label="用户名"
			placeholder="用户名"
			:rules="[{ required: true, message: '请填写用户名' }]"
	    />
	    <van-field
			v-model="data.password"
			type="password"
			name="pass"
			label="密码"
			placeholder="密码"
			:rules="[{ required: true, message: '请填写密码' }]"
	    />
	    <div style="margin: 16px">
			<van-button
				round
				block
				type="info"
				native-type="submit"
				color="#ffc400"
			>
	        注册
			</van-button>
			<van-button
				round
				block
				type="info"
				color="#ffc400"
				class="register"
				@click="toLogin"
			>
	        去登录
			</van-button>
	    </div>
	  </van-form>
	</div>
</template>

<script setup>
	import Header from "../../components/Header.vue";
	import { useRouter } from "vue-router";
	import { reactive, toRefs } from "vue";
	import { Toast } from "vant";
	
	const router = useRouter()
	
	const onSubmit = (value) => {
		console.log(value,'提交')
		if(localStorage.userInfo) {
			console.log('本地有存储信息，判断用户名是否重复')
			let userInfo = JSON.parse(localStorage.userInfo)
			if(userInfo['user'] === value['user']) {
				console.log('用户名重复')
				Toast('该用户已经存在')
				return
			}else {
				console.log('用户名可用，进行注册')
				register(value)
			}
		}else {
			console.log('本地没有信息，直接注册')
			register(value)
		}
	}
	
	const register = (value) => {
		localStorage.setItem('userInfo',JSON.stringify(value))
		Toast('注册成功')
		router.push('/login')
	}
	
	const toLogin = () => {
		router.push('/login')
	}
	
	const data = reactive({
		username: '',
		password: ''
	})
</script>

<style>
	.login {
	  .img {
	    width: 200px;
	    height: 200px;
	    background-color: #ffc400;
	    font-size: 80px;
	    line-height: 200px;
	    text-align: center;
	    border-radius: 40px;
	    margin: 20px auto;
	  }
	  .register {
	    margin-top: 20px;
	  }
	}
</style>